//导出提示
import { useState, useEffect } from "react";
import { Button, Progress } from "antd";
import CommonModal from "@/components/CommonModal";
import CommonLoading from "@/components/CommonLoading";
import { httpChange, GetChinese } from "@/utils/utils.jsx";
import { queryExportTaskRate, downLoadFileOp } from "../service";
import { message } from "antd";

const ExportModal = ({ taskId, visible, handleCancel, handleOk }) => {
	const [loading, setLoading] = useState(false);
	const [data, setData] = useState({});
	const [completed, setCompleted] = useState(false); //是否停止轮训

	const { exportedNum = 0, totalNum = 0 } = data;

	useEffect(() => {
		// 定时器变量
		let timer;
		if (!completed && visible) {
			// 轮询函数
			const startPolling = () => {
				handleCreateExportTask().finally(() => {
					// 安排下一次轮询
					timer = setTimeout(startPolling, 500);
				});
			};
			startPolling();
		}
		// 清理函数
		return () => {
			// 清除定时器
			clearTimeout(timer);
		};
	}, [completed, visible, taskId]);

	//查询导出进度
	const handleCreateExportTask = async () => {
		setLoading(true);
		const { data = {}, success } = await queryExportTaskRate({
			taskId: taskId
		});
		if (success) {
			setData(data);
			setCompleted(data?.completed);
		} else {
			handleCancel();
			setCompleted(true);
		}
		setLoading(false);
	};

	//导出文件
	const exportFile = url => {
		fetch(httpChange(url), {
			method: "GET"
		})
			.then(res => res.blob())
			.then(data => {
				const blobUrl = window.URL.createObjectURL(data);
				const a = document.createElement("a");
				a.download = GetChinese(url) + ".xlsx";
				a.href = httpChange(blobUrl);
				a.click();
			});
	};

	const handleClickExport = async () => {
		setLoading(true);
		const { data, success } = await downLoadFileOp({ id: taskId });
		if (success) {
			message.success("浏览器下载中，请稍后");
			exportFile(data);
		}
		setLoading(false);
	};

	//渲染进度条
	const renderRercent = () => {
		if (exportedNum && totalNum) {
			return (exportedNum / totalNum).toFixed(2) * 100;
		} else {
			return 0;
		}
	};

	//渲染底步按钮
	const footerRender = () => {
		if (completed) {
			return <Button type="primary" onClick={() => handleClickExport()}>下载表格</Button>;
		} else {
			return null;
		}
	};

	return (
		<CommonModal
			minHeight="100px"
			title={completed ? null : `正在批量更新中`}
			visible={visible}
			onCancel={handleCancel}
			onOk={handleOk}
			width="494px"
			footer={footerRender()}
		>
			<div style={{ textAlign: "center", marginBottom: "16px" }}>
				<Progress type="circle" percent={renderRercent()} />
				{completed ? <p>导出成功</p> : <p>正在导出，请稍等...</p>}
			</div>
			<CommonLoading loading={loading} />
		</CommonModal>
	);
};

export default ExportModal;
